<html>
<head>

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
    
/**  Load the Visualization API and the bar chart package. */
google.load("visualization", "1", {packages:['imagechart']});
      
/** Set a callback to run when the Google Visualization API is loaded. */
google.setOnLoadCallback(initializeData);

/** Once visualization API is loaded, retrieve spreadsheet data and set callback. */
function initializeData() {
  // Get all of the dorm data from the spreadsheet.
  var dormDataURL = 'https://spreadsheets.google.com/tq?key=0An9ynmXUoikYdF85ZmJlWkFtZmVIVFFvWWxnN0ItRHc&range=A2:G169&gid=5';
  var dormDataQuery = new google.visualization.Query(dormDataURL);
  // Set a callback to run when the dorm data has been retrieved.
  dormDataQuery.send(displayDormData);
}
      
/** Once dorm data is retrieved, create and display the chart with tooltips. */
function displayDormData(response) {
  // Process errors, if any.
  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }
  // Get the dorm data table.
  var data = response.getDataTable();

  // Make the image element.
  makeImageElement(data);

}

/**  Generate an img tag with a chart URL and an accompanying map element for displaying data.  */
function makeImageElement (data) {
  var img = document.createElement('img');
  img.setAttribute('src', getChartUrl(data));
  img.setAttribute('usemap', '#tooltipMap', 0);
  img.setAttribute('usemap', '#tooltipMap', 0);
  // Remove the blue line around the image.
  img.style.border = '0';
  document.getElementById('img').appendChild(img);
  document.getElementById('img').appendChild(createMap(data));

}

/**
 * Returns the URL for generating the chart.
 * Temporarily use the google visualization call to do it to simplify creation of the data parameter.
 * This results in 'flicker' and an extra HTTP call. 
 * We can generate the data param manually later in order to fix this.
 * Note we need to create a view containing just the (x,y,data) columns
 */
function getChartUrl(data) {
  // Create a view with just the x,y,value columns
  var view = new google.visualization.DataView(data);
  view.setColumns([2,3,4]);
  
  var chart = new google.visualization.ImageChart(document.getElementById('chart_div'));
  chart.draw(view, getOptions(data));

  // Get the URL without URL encoding of commas, pipes, and colons, since they take up too many characters and we have a 2K limit
  var chartUrl = chart.getImageUrl().replace(/%2C/g, ',').replace(/%7C/g, '|').replace(/%3A/g, ':');
  debug('Chart URL length is : ' + chartUrl.length);
  return chartUrl;
}

 
/** Build and return the options array for the chart. */
function getOptions(data) {
  // Set up the options 
  var options = {};
  // Scatter chart
  options.cht = 's';
  // Image size
  options.chs = '500x200';
  // X-axis (0) and Y-axis (1) labels
  options.chxl = '0:|' + getXAxisLabels(data) + '|1:|' + getYAxisLabels(data);
  // Adjust the X & Y axis with -1 so that dots line up correctly.
  // The last two numbers indicate the scaling range. 
  // Supply the lowest and highest value in the dataset to get automatic dot scaling. 
  var valueColumn = 4;
  options.chds = '-1,24,-1,7,0,' + getMaxColumnValue(data, valueColumn);
  // Shape marker: o = circle, 333333 = black, 1 = data series, -1 = allpoints, 20 = max size in pts.
  var maxSpotSize = 20;
  var defaultMarker = 'o,459E00,1,-1,' + maxSpotSize;
  options.chm = defaultMarker + getHighlightMarkers(data);
  options.enableEvents = true;
  return options;
}

/** Returns the maximum value found in the given column. */
function getMaxColumnValue(data, column) {
  var max = 0;
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    var currValue = data.getFormattedValue(i, column);
    if ( currValue > max) {
      max = currValue;
    }
  }
  debug('max was: ' + max);
  return max;
}

/** Return the marker strings for the hot spots that should be highlighted. */
function getHighlightMarkers(data) {
  var highlightColumn = 6;
  var highlightColor = 'FF0000';
  var testString = '|o,FF0000,1,13,5|o,FF0000,1,7,5';
  var xColumn = 2;
  var yColumn = 3
  var scaledColumn = 5;
  var returnString = '';
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    if (hasData(data, i, highlightColumn)) {
      returnString = returnString + 
	'|o,' + 
	highlightColor + ',' +
        '1' + ',' +
        i + ',' + 
        data.getFormattedValue(i, scaledColumn);
    }
  }
  debug('HighlightMarker string is: ' + returnString);
  return returnString;
}

/** Returns true if (row, column) in data has a value. */
function hasData(data, row, column) {
  return (data.getValue(row, column) != null);
}

/** Return the labels for the X Axis. */
function getXAxisLabels(data) {
  return '|12am|1|2|3|4|5|6|7|8|9|10|11|12pm|1|2|3|4|5|6|7|8|9|10|11|';
}

/** Return the labels for the Y Axis. */
function getYAxisLabels(data) {
  return '|Sun|Mon|Tue|Wed|Thr|Fri|Sat|';
}
 

/** Create and return the image map element.  */
function createMap(data) {
  var map = document.createElement('map');
  map.setAttribute('id', 'tooltipMap');
  map.setAttribute('name', 'tooltipMap');

  // Initial offset into the chart to get the map aligned with the (x,y) values.
  // (47, 158) is the position of the bottom left dot
  var yOffset = 158;   
  var xOffset = 47;    
  var columnWidth = 18.5;
  var rowHeight = 21.5;
  var mapRadius = 8;

  // The numbers corresponding to the columns parts in the data object.
  var hourColumn = 0;
  var dayColumn = 1;
  var xColumn = 2;
  var yColumn = 3
  var valueColumn = 4;

  // loop through all the data points.
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    // Get the x and y values.
    var y = data.getFormattedValue(i, yColumn);
    var x = data.getFormattedValue(i, xColumn);
    var label = 
      data.getFormattedValue(i,dayColumn) + ' ' +
      data.getFormattedValue(i,hourColumn) + ': ' +
      data.getFormattedValue(i,valueColumn) + ' watt-hrs';

    var area = document.createElement('area');
    area.setAttribute('id', '' + i);
    area.setAttribute('shape', 'circle');
    var xCoord = (xOffset + (columnWidth * x));
    var yCoord = (yOffset - (rowHeight * y));
    area.setAttribute('coords', '' + xCoord + ',' + yCoord +',' + mapRadius);
    area.setAttribute('nohref', 'nohref');
    area.setAttribute('onmouseover', 'showTooltip(\'' + label + '\',' + xCoord + ',' + yCoord + ');');
    area.setAttribute('onmouseout', 'hideTooltip();');
    map.appendChild(area);
  }
  return map;
}

function showTooltip(label, xCoord, yCoord) {
  var tooltip = document.getElementById('tooltip');
  tooltip.style.left = (xCoord + 20) + 'px';
  tooltip.style.top = (yCoord + 20) + 'px';
  tooltip.style.width = 'auto'; 
  tooltip.style.height = 'auto'; 
  tooltip.style.position = 'absolute';
  tooltip.style.background = '#fff';
  tooltip.innerHTML = label;
  tooltip.style.borderStyle = 'solid';
  tooltip.style.borderWidth = 'thin';
  tooltip.style.color = '459E00';
  tooltip.style.visibility = 'visible';
}

function hideTooltip() {
  document.getElementById('tooltip').style.visibility='hidden';
}

/**
 * Outputs the message to the Firebug console window (if console is defined).
 */
function debug(msg) {
  if (typeof(console) != 'undefined') {
    console.info(msg);
  }
}

</script>
</head>

<body>
  <div style="text-indent: 50px; font-weight: bold; color: #459E00">Hale Ilima: Energy Consumption during the last 7 days</div>
  <div id="tooltip"></div>
  <div id="img"></div>
  <div style="margin-left: 20px; width: 470px">
    <p>
    This visualization shows the relative level of energy consumption over
    the past 7 days for a single dormitory. The size of the dot indicates
    the relative energy consumption during that hour.  Moving the mouse
    over a dot reveals a tooltip with further information about that dot.
    You can use this visualization to look for trends in energy data, such
    as days (rows) or hours of the day (columns) with relatively large (or
    small) consumption.
  </div>
    
  <div style="display: none" id="chart_div"></div>
</body>
</html>

